package com.jd.controller;

import com.jd.entity.Book;
import com.jd.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ProjectName: soft3->BookController
 * Description: 表示层，依赖service
 * Author: 丘丘
 * DateTime: 2024/12/24 22:00
 */

@RestController
@RequestMapping("/book")
@CrossOrigin
public class BookRestController {
    @Autowired
    private BookService bookService;

    // 结果就两大类，要么成功，返回成功码和数据，要么失败，返回失败码和失败提示
    private R success(Object data) {
        return new R(200, data);
    }

    private R failure(String msg) {
        return new R(500, msg);
    }


    @GetMapping()
    public R selectAllBooks() {
        List<Book> books = bookService.selectAllBooks();
        return books != null && !books.isEmpty() ?
                success(books) :
                failure("暂无内容");
    }


    @GetMapping("/{id}")
    public Book selectBookById(@PathVariable String id) {
        Book book = bookService.selectBookById(Integer.parseInt(id));
        return book != null ?
                success(book):
                failure("无内容");

    }

    @DeleteMapping("/{id}")
    public R deleteBookById(@PathVariable String id) {
        Boolean aBoolean = bookService.deleteBookById(Integer.parseInt(id));
        return  aBoolean?
                success("删除成功"):
                failure("删除失败");
    }

    @PostMapping()
    public R insertBook(@RequestBody Book book) {
        Boolean aBoolean = bookService.insertBook(book);
        return aBoolean ?
                success("添加成功"):
                failure("添加失败");
    }

    @PutMapping()
    public R updateBook(@RequestBody Book book) {
        Boolean aBoolean = bookService.updateBook(book);
        return aBoolean?
                success("修改成功"):
                failure("修改失败");
    }

    @GetMapping(params = "bookName")
    public R selectBookByName(String bookName) {
        List<Book> bookList = bookService.selectBookByName(bookName);
        System.out.println("bookList = " + bookList);
        System.out.println("bookName = " + bookName);
        return bookList!=null && !bookList.isEmpty() ?
                success(bookList):
                failure("没有内容");
    }


}
